import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sinosheets/components/NetWorkImage/NetworkImageWidget.dart';
import 'package:sinosheets/components/gb_alert.dart';
import 'package:sinosheets/r.dart';
import 'package:sinosheets/utils/currency_util.dart';
import 'package:sinosheets/utils/gb_time_utils.dart';
import 'package:sinosheets/utils/parse_util.dart';
import 'package:sinosheets/utils/theme/style_utils.dart';

//使用页面的类型 1.列表 2.详情
enum ShippingLineType {
  list,
  detail,
}

/// 缴税方式枚举
enum TaxType {
  platformGst(value: 1),
  platformIoss(value: 2),
  personGst(value: 3),
  personIoss(value: 4),
  receiver(value: 5),
  free(value: 6);

  const TaxType({required this.value});

  final int value;

  static TaxType parse(int? value) {
    if (value == 1) {
      return TaxType.platformGst;
    }
    if (value == 2) {
      return TaxType.platformIoss;
    }
    if (value == 3) {
      return TaxType.personGst;
    }
    if (value == 4) {
      return TaxType.personIoss;
    }
    if (value == 5) {
      return TaxType.receiver;
    }
    if (value == 6) {
      return TaxType.free;
    }

    return TaxType.platformGst;
  }
}

class ShippingLineCell extends StatelessWidget {
  const ShippingLineCell({
    super.key,
    required this.lineMap,
    this.onSelectClick,
    this.showDetail = true,
    this.showSelect = true,
    this.isBigHeader = false,
    required this.type,
  });

  final Map lineMap;
  final void Function()? onSelectClick;
  final bool showDetail;
  final bool showSelect;
  final ShippingLineType type;
  final bool isBigHeader;

  @override
  Widget build(BuildContext context) {
    /// 是否选中
    bool select = lineMap["select"] ?? false;

    /// 是否可用
    bool enable = lineMap["enable"] ?? false;

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if (!enable) {
          return;
        }
        if (!showSelect) {
          return;
        }
        if (onSelectClick != null) {
          onSelectClick!();
        }
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.r, vertical: 12.r),
        decoration: BoxDecoration(
          color: type == ShippingLineType.list
              ? enable
                  ? ColorUtils.c_ffffff
                  : ColorUtils.c_f3f3f3
              : ColorUtils.c_ffffff,
          borderRadius: BorderRadius.circular(12.r),
          border: select && type == ShippingLineType.list
              ? Border.all(
                  color: ColorUtils.themeColor,
                  width: 1,
                )
              : null,
        ),
        child: Column(
          children: [
            headerWidget(),
            overviewWidget(),
          ],
        ),
      ),
    );
  }

  /// 头部的名称，图标
  Widget headerWidget() {
    String iconUrl = lineMap["iconUrl"] ?? "";
    String lineName = lineMap["lineName"] ?? "";

    /// 是否显示免税；
    bool isTaxFree = false;
    List lineDeclareConfigVOs = lineMap["lineDeclareConfigVOs"] ?? [];
    if (lineDeclareConfigVOs.isNotEmpty) {
      for (Map config in lineDeclareConfigVOs) {
        int registrationType = config["registrationType"] ?? 0;
        TaxType type = TaxType.parse(registrationType);
        if (TaxType.free == type) {
          isTaxFree = true;
          break;
        }
      }
    }

    ///是否显示保险 safeguardResponse字段不为null即有保险
    bool showSafeguard = false;
    Map safeguardResponse = lineMap["safeguardResponse"] ?? {};
    if (safeguardResponse.isNotEmpty) {
      showSafeguard = true;
    }
    String remind = "";

    /// 线路名称长度限制
    double lineMaxWidth = Get.width;
    lineMaxWidth -= 2 * (12.r + 12.r); // padding和margin
    lineMaxWidth -= 30.r; // 线路图标
    if (showSelect && type == ShippingLineType.list) {
      lineMaxWidth -= 20.r; // 选择图标
    }
    if (type == ShippingLineType.detail) {
      lineMaxWidth -= 100.r; // 查看详情
    }
    if (isTaxFree) {
      lineMaxWidth -= 80.r; // 免税
    }
    if (showSafeguard) {
      lineMaxWidth -= 20.r; // 运输无忧
    }
    LogUtil.e("lineMaxWidth: $lineMaxWidth");

    int maxLines = 1;
    if (isBigHeader) {
      maxLines = 10;
    }

    return Container(
      constraints: BoxConstraints(
        minHeight: 40.r,
      ),
      padding: EdgeInsets.symmetric(vertical: 8.r),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              /// 有保险，并且remind字段不为空，显示保险介绍
              if (!(showSafeguard && remind.isNotEmpty)) {
                return;
              }

              double alertHeight = 400.r;
              double contentHeight = alertHeight - 130.r;
              GBAlert.show(
                title: "safeguard_title".tr,
                height: alertHeight,
                content: SizedBox(
                  height: contentHeight,
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Text("safeguard_line_tip".tr, style: StyleUtils.ts_33_15_400.copyWith(color: ColorUtils.c_00cb48)),
                        SizedBox(height: 10.r),
                        Text(
                          remind,
                          style: StyleUtils.ts_33_15_400,
                        ),
                      ],
                    ),
                  ),
                ),
                buttonType: GBAlertButtonType.oneButton,
              );
            },
            child: Row(
              children: [
                Container(
                  width: 20.r,
                  height: 20.r,
                  clipBehavior: Clip.antiAlias,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10.r),
                  ),
                  child: NetworkImageWidget(url: iconUrl),
                ),
                SizedBox(width: 8.r),
                Container(
                  constraints: BoxConstraints(
                    maxWidth: lineMaxWidth,
                  ),
                  child: Text(
                    lineName,
                    style: StyleUtils.ts_1f_16_500,
                    maxLines: maxLines,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                SizedBox(width: 4.r),
                Visibility(
                  visible: isTaxFree,
                  child: Container(
                    height: 15.r,
                    padding: EdgeInsets.symmetric(horizontal: 6.r),
                    decoration: BoxDecoration(
                      color: ColorUtils.themeColor.withValues(alpha: 0.08),
                      borderRadius: BorderRadius.circular(7.5.r),
                      border: Border.all(
                        color: ColorUtils.themeColor,
                        width: 0.5,
                      ),
                    ),
                    child: Center(
                      child: Text(
                        "tax_free".tr,
                        style: StyleUtils.ts_theme_10_600,
                      ),
                    ),
                  ),
                ),
                SizedBox(width: 4.r),
                Visibility(
                  visible: showSafeguard,
                  child: Image.asset(
                    R.assetsImgIconSafe,
                    width: 16.r,
                    height: 16.r,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 线路概况
  Widget overviewWidget() {
    bool enable = lineMap["enable"] ?? true;
    double feeWidth = Get.width - 2 * (10.r + 12.r + 12.r) - 10.r;
    feeWidth /= 2;

    /// 寄送周期
    String transitTime = lineMap["transitTime"] ?? "";

    /// 费用和折扣
    Map freightEstimateFeeVO = lineMap["freightEstimateFeeVO"] ?? {};
    double feeTotal = freightEstimateFeeVO["feeTotal"] ?? 0;
    double feeFinal = freightEstimateFeeVO["feeFinal"] ?? 0;
    int discountStatus = freightEstimateFeeVO["discountStatus"] ?? 0;
    bool hasDiscount = (discountStatus == 1);

    /// 折扣
    Map lineConfigFeeVO = lineMap["lineConfigFeeVO"] ?? {};
    double discountRate = lineConfigFeeVO["discountRate"] ?? 0;
    String discountStartTime = lineConfigFeeVO["discountStartTime"] ?? "";
    String discountEndTime = lineConfigFeeVO["discountEndTime"] ?? "";
    String discountText = "";
    if (discountEndTime.isNotEmpty) {
      Map remain = GBTimeUtils.getRemainingTime(discountEndTime, withSecond: false);
      String timeString = remain["timeString"] ?? "";
      if (timeString.isNotEmpty) {
        discountText = "${"activity_remain".tr}$timeString";
      }
    }

    /// 是否显示折扣： 有折扣，并且在活动期间
    bool isActive = GBTimeUtils.isActive(discountStartTime, discountEndTime);
    bool showDiscount = (hasDiscount && isActive);

    /// 计费重量
    Map freightEstimateSizeVO = lineMap["freightEstimateSizeVO"] ?? {};
    double finalWeight = ParseUtil.parseDouble(freightEstimateSizeVO["finalWeight"]);
    int weightType = ParseUtil.parseInt(freightEstimateSizeVO["weightType"]);
    String suffixText;
    if (weightType == 1) {
      suffixText = "volumetric".tr;
    } else {
      suffixText = "actual".tr;
    }

    /// 禁用原因
    List reasonList = lineMap["reasonList"] ?? [];
    String reasonText = reasonList.join("/");

    return Stack(
      children: [
        Container(
          height: 44.r,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [
                ColorUtils.c_fdf3ec,
                ColorUtils.c_ffffff,
              ],
            ),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(8.r),
              topRight: Radius.circular(8.r),
            ),
          ),
        ),
        Column(
          children: [
            Visibility(
              visible: showDiscount,
              child: Container(
                height: 32.r,
                padding: EdgeInsets.symmetric(horizontal: 8.r),
                child: Row(
                  children: [
                    Icon(
                      Icons.local_fire_department,
                      color: ColorUtils.themeColor,
                      size: 14.r,
                    ),
                    SizedBox(width: 2.r),
                    Text("limited_time_offer".tr, style: StyleUtils.ts_theme_12_600),
                    SizedBox(width: 8.r),
                    FlexTextWidget(discountText, StyleUtils.ts_1f_11_500),
                  ],
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 12.r, vertical: 12.r),
              decoration: BoxDecoration(
                color: ColorUtils.c_f8f8f8,
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Column(
                children: [
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      if (!showDetail) {
                        return;
                      }

                      /// 去详情页
                      // RouteUtils.openShippingLineDetail(lineMap);
                    },
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("line_overview".tr, style: StyleUtils.ts_1f_13_500),
                          ],
                        ),
                        SizedBox(height: 14.r),
                      ],
                    ),
                  ),
                  Row(
                    children: [
                      Container(
                        padding: EdgeInsets.only(right: 10.r),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Text("${"fee".tr}(${CurrencyUtil.getSymbol()})", style: StyleUtils.ts_99_11_400),
                                SizedBox(width: 4.r),
                                Visibility(
                                  visible: showDiscount,
                                  child: Container(
                                    height: 15.r,
                                    padding: EdgeInsets.symmetric(horizontal: 5.r),
                                    decoration: BoxDecoration(
                                      color: ColorUtils.c_fd5155,
                                      borderRadius: BorderRadius.circular(7.5.r),
                                    ),
                                    child: Row(
                                      children: [
                                        Text("-${discountRate.toStringAsFixed(0)}%", style: StyleUtils.ts_ff_8_500),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(height: 4.r),
                            Row(
                              children: [
                                Container(
                                  constraints: BoxConstraints(
                                    maxWidth: feeWidth / 2,
                                  ),
                                  child: FittedBox(
                                    fit: BoxFit.scaleDown,
                                    child: Text(CurrencyUtil.rmbToCurrencyAmount(feeFinal, withSymbol: false), style: StyleUtils.ts_1f_18_500),
                                  ),
                                ),
                                Visibility(
                                  visible: showDiscount,
                                  child: Container(
                                    constraints: BoxConstraints(
                                      maxWidth: feeWidth / 2,
                                    ),
                                    child: FittedBox(
                                      fit: BoxFit.scaleDown,
                                      child: Text(CurrencyUtil.rmbToCurrencyAmount(feeTotal, withSymbol: false), style: StyleUtils.ts_99_12_400_th),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child: Center(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              FittedBox(
                                fit: BoxFit.scaleDown,
                                child: Text(
                                  "${"billing_weight".tr}($suffixText)",
                                  style: StyleUtils.ts_99_11_400,
                                  textAlign: TextAlign.center,
                                  maxLines: 1,
                                ),
                              ),
                              SizedBox(height: 4.r),
                              Text(
                                "${finalWeight.toStringAsFixed(0)}(g)",
                                style: StyleUtils.ts_1f_18_500,
                                textAlign: TextAlign.center,
                              ),
                            ],
                          ),
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.only(left: 10.r),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("efficiency".tr, style: StyleUtils.ts_99_11_400),
                            SizedBox(height: 4.r),
                            Text("$transitTime${"day".tr}", style: StyleUtils.ts_1f_18_500),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Visibility(
              visible: !enable,
              child: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () async {
                  await GBAlert.show(
                    title: 'line_disable_reason'.tr,
                    buttonType: GBAlertButtonType.oneButton,
                    height: 300.r,
                    content: SizedBox(
                        height: 160.r,
                        child: ListView(
                          padding: EdgeInsets.zero,
                          shrinkWrap: true,
                          children: [
                            Text(
                              reasonText,
                              style: StyleUtils.ts_ff_12_500,
                              overflow: TextOverflow.ellipsis,
                              maxLines: 10,
                            )
                          ],
                        )),
                  );
                },
                child: Container(
                  margin: EdgeInsets.only(top: 8.r),
                  child: Row(
                    children: [
                      Icon(Icons.info, color: ColorUtils.c_999999, size: 16.r),
                      SizedBox(width: 4.r),
                      Expanded(
                        child: Text(
                          reasonText,
                          style: StyleUtils.ts_99_12_400,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                        ),
                      ),
                      SizedBox(width: 8.r),
                      Icon(
                        Icons.chevron_right,
                        color: ColorUtils.c_999999,
                        size: 16.r,
                      )
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }
}

class FlexTextWidget extends StatelessWidget {
  const FlexTextWidget(
    this.data,
    this.style, {
    super.key,
    this.flex = 1,
    this.maxLines = 1,
  });

  final String data;
  final int flex;
  final TextStyle style;
  final int maxLines;

  @override
  Widget build(BuildContext context) {
    return Flexible(
      flex: flex,
      child: Text(
        data,
        style: style,
        maxLines: maxLines,
        overflow: TextOverflow.ellipsis,
      ),
    );
  }
}
